package com.ewerp.mud.core.session;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.ewerp.mud.core.lifecycle.ILifecycleListener;
import com.ewerp.mud.core.plugin.IPlugin;

public class TestEwerpSessionManager {
    private ISessionManager sessionManager = null;

    ISession mockSession = null;
    
    @Before
    public void setup() {
        sessionManager = EwerpSessionManager.getInstance();
        mockSession = new MockSession();
    }

    @After
    public void breakDown() {

    }
    
    @Test
    public void testPluginType() {
        assertTrue(((IPlugin)sessionManager).getInterfaces().contains(ISessionManager.class));
    }
    
    @Test (expected = IllegalArgumentException.class)
    public void testAddNullSession() {
        sessionManager.addSession(null);
    }
    
    @Test (expected = IllegalArgumentException.class)
    public void testRemoveNullSession() {
        sessionManager.removeSession(null);
    }
    
    @Test
    public void testAddNewSession() {
        assertFalse(((EwerpSessionManager)sessionManager).getSessionList().contains(mockSession));
        sessionManager.addSession(mockSession);
        assertTrue(((EwerpSessionManager)sessionManager).getSessionList().contains(mockSession));
    }
    
    @Test
    public void testRemoveNewSession() {
        if(!((EwerpSessionManager)sessionManager).getSessionList().contains(mockSession)) {
            testAddNewSession();
        }
        sessionManager.removeSession(mockSession);
        assertFalse(((EwerpSessionManager)sessionManager).getSessionList().contains(mockSession));
    }
    
    @Test
    public void testShutdownOfSessions() {
        MockSession session = new MockSession();
        assertEquals(0, session.getMethodInvocationCount("shutdown"));
        
        sessionManager.addSession(session);
        ((ILifecycleListener)sessionManager).stop();

        assertEquals(1, session.getMethodInvocationCount("shutdown"));
    }
    
    @Test
    public void testSessionFactoryLifecycle() {
        MockSessionFactory sessionFactory = new MockSessionFactory();
        
        ((EwerpSessionManager)sessionManager).addSessionFactory(sessionFactory);
        
        assertEquals(0, sessionFactory.getMethodInvocationCount("registerSessionManager"));
        
        ((ILifecycleListener)sessionManager).init();
        ((ILifecycleListener)sessionManager).start();
        ((ILifecycleListener)sessionManager).stop();
        
        assertEquals(1, sessionFactory.getMethodInvocationCount("registerSessionManager"));
    }
    
}
